package com.hmitkov.musicplayer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;

public class PlayService extends Service implements OnCompletionListener {

	private MediaPlayer mp;
	private int currentSongIndex = 0;
	private boolean isShuffle = false;
	private boolean isRepeat = false;
	private int seekForwardTime = 5000; // 5000 milliseconds
	private int seekBackwardTime = 5000; // 5000 milliseconds
	private ArrayList<HashMap> songsList = new ArrayList<HashMap>();

	WifiLock mWifiLock;
	AudioManager mAudioManager;
    NotificationManager mNotificationManager;
    AudioFocus mAudioFocus = AudioFocus.NoFocusNoDuck;
    Notification mNotification = null;
    
    final int NOTIFICATION_ID = 1;
    enum AudioFocus {
        NoFocusNoDuck,    // we don't have audio focus, and can't duck
        NoFocusCanDuck,   // we don't have focus, but can play at a low volume ("ducking")
        Focused           // we have full audio focus
    }
    
	public static PlayService instance = null;

	@Override
	public void onCreate() {
		super.onCreate();
		instance = this;

		mWifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");

		mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (mp != null) {
			mp.release();
			mp = null;
		}
		mp = new MediaPlayer();

		mp.setOnCompletionListener(this); // Important

		// Getting all songs list
		songsList = SongsManager.instance.getPlayList(this);

		// By default play first song
//		if (songsList.size() > 0) {
//			playSong(currentSongIndex);
//		}
		return Service.START_NOT_STICKY;
	}

	public class MyBinder extends Binder {
		PlayService getService() {
			return PlayService.this;
		}
	}
	public void playSong(){
		playSong(currentSongIndex);
	}
	public void playSong(int songIndex) {
		currentSongIndex=songIndex;
		try {
			mp.reset();
			if (SongsManager.instance.files == null || SongsManager.instance.files.length==0) {
				AssetFileDescriptor afd = (AssetFileDescriptor) songsList.get(songIndex).get("songPath");
				mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());

			} else {

				mp.setDataSource((String) songsList.get(songIndex).get("songPath"));
			}
			mp.prepare();
			mp.start();
			setUpAsForeground((String)songsList.get(songIndex).get("songTitle"));
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * On Song Playing completed if repeat is ON play same song again if shuffle
	 * is ON play random song
	 * */
	@Override
	public void onCompletion(MediaPlayer arg0) {

		// check for repeat is ON or OFF
		if (isRepeat) {
			// repeat is on play same song again
			playSong(currentSongIndex);
		} else if (isShuffle) {
			// shuffle is on - play a random song
			Random rand = new Random();
			currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
			playSong(currentSongIndex);
		} else {
			// no repeat or shuffle ON - play next song
			if (currentSongIndex < (songsList.size() - 1)) {
				playSong(currentSongIndex + 1);
				currentSongIndex = currentSongIndex + 1;
			} else {
				// play first song
				playSong(0);
				currentSongIndex = 0;
			}
		}
	}

	public boolean btnPlay() {
		// check for already playing
		if (mp.isPlaying()) {
			mp.pause();
			return false;
		} else {
			mp.start();
			return true;
		}
	}

	public void forward() {
		// get current song position
		int currentPosition = mp.getCurrentPosition();
		// check if seekForward time is lesser than song duration
		if (currentPosition + seekForwardTime <= mp.getDuration()) {
			// forward song
			mp.seekTo(currentPosition + seekForwardTime);
		} else {
			// forward to end position
			mp.seekTo(mp.getDuration());
		}
	}

	public void backward() {
		// get current song position
		int currentPosition = mp.getCurrentPosition();
		// check if seekBackward time is greater than 0 sec
		if (currentPosition - seekBackwardTime >= 0) {
			// forward song
			mp.seekTo(currentPosition - seekBackwardTime);
		} else {
			// backward to starting position
			mp.seekTo(0);
		}
	}

	public boolean repeat() {
		if (isRepeat) {
			isRepeat = false;
		} else {
			// make repeat to true
			isRepeat = true;
			// make shuffle to false
			isShuffle = false;
		}
		return isRepeat;
	}

	public boolean shuffle() {
		if (isShuffle) {
			isShuffle = false;
		} else {
			// make repeat to true
			isShuffle = true;
			Toast.makeText(getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();
			// make shuffle to false
			isRepeat = false;
		}
		return isShuffle;
	}

	int getDuration() {
		return mp.getDuration();
	}

	int getCurrentPosition() {
		return mp.getCurrentPosition();
	}

	void seekTo(int msec) {
		mp.seekTo(msec);
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	void releaseResources() {
        // stop being a foreground service
        stopForeground(true);

        // stop and release the Media Player, if it's available
        if (mp != null) {
            mp.reset();
            mp.release();
            mp = null;
        }

        // we can also release the Wifi lock, if we're holding it
        if (mWifiLock.isHeld()) mWifiLock.release();
    }
	 @Override
	    public void onDestroy() {
	        releaseResources();

	        instance=null;
	    }
	    void setUpAsForeground(String text) {
	        PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,
	                new Intent(getApplicationContext(), MusicPlayerActivity.class),
	                PendingIntent.FLAG_UPDATE_CURRENT);
	        mNotification = new Notification();
	        mNotification.tickerText = text;
	        mNotification.icon = R.drawable.img_btn_play;
	        mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
	        mNotification.setLatestEventInfo(getApplicationContext(), "RandomMusicPlayer",
	                text, pi);
	        startForeground(NOTIFICATION_ID, mNotification);
	    }

		public MediaPlayer getMp() {
			return mp;
		}

		public void setMp(MediaPlayer mp) {
			this.mp = mp;
		}

		public int getCurrentSongIndex() {
			return currentSongIndex;
		}

		public void setCurrentSongIndex(int currentSongIndex) {
			this.currentSongIndex = currentSongIndex;
		}
	    

}
